package com.idea.relax.boot.config;

import com.idea.relax.boot.cors.RelaxCorsProperties;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 跨域配置
 * @author salad
 */
@Configuration
@AllArgsConstructor
@EnableConfigurationProperties(RelaxCorsProperties.class)
@ConditionalOnProperty(prefix = RelaxCorsProperties.PREFIX, name = ".enabled")
public class CorsConfiguration implements WebMvcConfigurer {

	private final RelaxCorsProperties properties;

	@Override
	public void addCorsMappings(CorsRegistry registry) {
		// 跨域路径
		registry.addMapping(properties.getPathPattern())
			// 可访问的外部域
			.allowedOrigins(properties.getAllowedOrigins())
			// 支持跨域用户凭证
			//.allowCredentials(true)
			//.allowedOriginPatterns("*")
			// 设置 header 能携带的信息
			.allowedHeaders(properties.getAllowedHeaders())
			// 支持跨域的请求方法
			.allowedMethods(properties.getAllowedMethods())
			// 设置跨域过期时间，单位为秒
			.maxAge(properties.getMaxAge());
	}

}
